import ctypes
import numpy as np
libtest = ctypes.cdll.LoadLibrary('./distance/xh_dis.so')

def edit_distance(arr1, arr2):
	return (libtest.get_distance(
		(ctypes.c_int * len(arr1))(*arr1),
		(ctypes.c_int * len(arr2))(*arr2),
		len(arr1),
		len(arr2)))


def get_distance_between_lists(s1, s2, a1, a2, m, n, dists):
	idx1=0
	for a in range(m):
		idx2=0
		for b in range(n):
			distances=np.zeros([a1[a]+1,a2[b]+1])
			for i in range(a1[a]+1):
				distances[i][0]=i
			for j in range(a2[b]+1):
				distances[0][j] =j
			for i in range(1,a1[a]+1):
				for j in range(1,a2[b]+1):
					if s1[idx1+i-1]==s2[idx2+j-1]:
						distances[i][j]=distances[i-1][j-1]
					else:
						distances[i][j]=1+min(distances[i-1][j],distances[i][j-1],distances[i-1][j-1])
			dists[a*n+b]=distances[a1[a]][a2[b]]
			idx2+=a2[b]
		idx1+=a1[a]


def get_ed_btwn_lists(arr1, arr2, arr3, arr4):
	'''
	input:
		arr1: a list
		arr2: a list
		m: int, namely length of arr3[]
		n: length of arr4[]
	output:
		result: a list
	usage:
		The example is in main()
	'''
	m = int(len(arr3))
	n = int(len(arr4))
	# buffering = (ctypes.c_int * ( m * n ))()
	# print('getdis:btwn')
	buffering = np.zeros(m*n)
	# print(arr1)
	# print(arr2)
	# libtest.get_distance_between_lists(
	# 		(ctypes.c_int * len(arr1)) (*arr1),
	# 		(ctypes.c_int * len(arr2)) (*arr2),
	# 		(ctypes.c_int * len(arr3)) (*arr3),
	# 		(ctypes.c_int * len(arr4)) (*arr4),
	# 		m,
	# 		n,
	# 		buffering
	# 	)
	idx1=0
	for a in range(m):
		print(f'a={a}')
		idx2=0
		for b in range(n):
			distances=np.zeros([arr3[a]+1,arr4[b]+1])
			for i in range(arr3[a]+1):
				distances[i][0]=i
			for j in range(arr4[b]+1):
				distances[0][j] =j
			for i in range(1,arr3[a]+1):
				for j in range(1,arr4[b]+1):
					if arr1[idx1+i-1]==arr2[idx2+j-1]:
						distances[i][j]=distances[i-1][j-1]
					else:
						distances[i][j]=1+min(distances[i-1][j],distances[i][j-1],distances[i-1][j-1])
			buffering[a*n+b]=distances[arr3[a]][arr4[b]]
			idx2+=arr4[b]
		idx1+=arr3[a]
	print('222')
	result = []
	for i in range(m*n):
		result.append( buffering[i] )
	return result

if __name__ == '__main__':
# wrong example:
#	arr1 = [[1,2,3,3,4],[20,20],[20,20]]
#	arr2 = [[1,5,3,4],[30,30,30],[30,30,30]]
# correct example:
	arr1 = [1,2,3,3,4,20,20,20,20]
	arr2 = [1,5,3,4,30,30,30,30,30,30]
	arr3 = [5,2,2]
	arr4 = [4,3,3]
	result = get_ed_btwn_lists(arr1, arr2, arr3, arr4)
# 	result: [2,5,5,4,3,3,4,3,3]	
	print(result)	

#	print(type(buff))
#	<class '__main__.c_int_Array_9'>

#	print(buff)
#	<__main__.c_int_Array_9 object at 0x...>
#	for i in range(9):
#		print(buff[i])
